import { createRouter, createWebHistory } from 'vue-router'
import useUser from '@/stores/useUser'
import { storeToRefs } from 'pinia'
export const menuRoutes = [
  {
    path: '/auth',
    name: '权限管理',
    meta: {
      code: 'RBAC'
    },
    children: [
      {
        path: '/staff-list',
        name: '员工管理',
        meta: {
          code: 'EmployList'
        },
        component: () => import('@/views/Staff/List.vue')
      },
      {
        path: '/role-list',
        name: '部门管理',
        meta: {
          code: 'PortList'
        },
        component: () => import('@/views/Role/List.vue')
      },
      {
        path: '/auth-list',
        name: '视图管理',
        meta: {
          code: 'ViewManage'
        },
        component: () => import('@/views/Auth/List.vue')
      }
    ]
  },
  {
    path: '/big-screen',
    name: '大屏管理',
    meta: {
      code: 'BigScreen'
    },
    component: () => import('@/views/BigScreen/Index.vue')
  },
  {
    path: '/group-manage',
    name: '团购管理',
    meta: {
      code: 'GroupBuyManage'
    },
    component: () => import('@/views/Group/Index.vue')
  }
]
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/', redirect: 'home' },
    { path: '/404', name: '404', component: () => import('@/views/404.vue') },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/Login.vue')
    },
    {
      path: '/home',
      name: 'home',
      redirect: '/staff-list',
      component: () => import('../views/Home.vue'),
      children: menuRoutes
    }
  ]
})
const AuthWhiteList = ['/login', '/404']
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  if (to.path === '/login') {
    if (token) {
      next('/')
    } else {
      next()
    }
    next()
  } else {
    if (token) {
      const { userInfo } = storeToRefs(useUser())
      console.log(userInfo.value)
      console.log(to)
      if (AuthWhiteList.includes(to.path)) {
        next()
      } else if (userInfo.value && userInfo.value?.authCodes.includes(to.meta.code as string)) {
        next()
      } else {
        next('/404')
      }
    } else {
      next('/login')
    }
  }
})
export default router

const treeData = [
  { name: 'root', code: null },
  {
    name: 'a',
    code: 1,
    pcode: null,
    childList: {
      name: 'b',
      id: 101,
      children: {
        name: 'c',
        id: 10101
      }
    }
  }
]

const data = [
  { name: 'a', code: 1 },
  { name: 'b', code: 101, pcode: 1 },
  { name: 'c', code: 10101, pcode: 101 }
]
